package edu.odu.cs.sstore.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import edu.odu.cs.sstore.domain.User;
import edu.odu.cs.sstore.repository.UserRepository;

@Service
public class UserContextService {

	@Autowired
	private UserRepository userRepository;
	
	@Transactional(readOnly=true)
	public User getCurrentUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Object principal = authentication.getPrincipal();
		
		System.out.println(principal);
		
		String username = null;
		if (principal instanceof UserDetails) {
			username = ((UserDetails)principal).getUsername();
		} else {
			username = principal.toString();
		}
		
		if(username == null)
			return null;

		return this.userRepository.findByUserName(username);
	}
	
}
